package cn.com.sinosoft.ares.insurance.service;

import cn.com.sinosoft.ares.insurance.dao.CardusedDao;
import cn.com.sinosoft.ares.insurance.dao.PrpDCompanyDao;
import cn.com.sinosoft.ares.insurance.dao.PrpDUserDao;
import cn.com.sinosoft.ares.insurance.model.CardUsed;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;

/**
 * Description: 承保抽象类
 * Author: lishangmin
 * Created: 2018-09-05 10:38
 */
public abstract class AbstractInsureService<R,Q> implements IInsureService<R,Q>{

    @Autowired
    PrpDUserDao prpDUserDao;

    @Autowired
    PrpDCompanyDao prpDCompanyDao;

    /**
     * 根据用户名获取机构代码
     * @param userName 用户名
     * @return 机构代码
     */
    protected String getComCode(String userName){
        return prpDUserDao.selectComCodeByPrimaryKey(userName);
    }

    /**
     * 根据旧的机构代码获取新的机构代码
     * @param comCode 旧的机构代码
     * @return 新的机构代码
     */
    protected String getNewComCode(String comCode){
        String newComCode = "";
        if(StringUtils.isNotEmpty(comCode)){
            newComCode = prpDCompanyDao.selectNewComCodeByComCode(comCode);
        }
        return newComCode;
    }

    @Autowired
    CardusedDao cardusedDao;

    /**
     * 生成保单号或者投保单号
     * @param comCode  机构代码
     * @param riskCode 风险代码
     * @param prefix   前缀
     * @return 保单号/投保单号
     */
    public String getPolicyNo(String comCode, String riskCode, String prefix) {
        String newYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) ;
        comCode= comCode.substring(0,6);
        String serialNo= "000001";
        CardUsed cardUsed = cardusedDao.selectByPrimaryKey(comCode, riskCode, newYear, prefix);
        if (null == cardUsed || "".equals(cardUsed.getSerialno())) {
            CardUsed cardUser = new CardUsed();
            cardUser.setComcode(comCode);
            cardUser.setRiskcode(riskCode);
            cardUser.setSerialno(serialNo);
            cardUser.setYears(newYear);
            cardUser.setType(prefix);
            cardusedDao.insert(cardUser);
        } else {
            serialNo = noComplete(Integer.parseInt(cardUsed.getSerialno())+1,6);
            cardUsed.setSerialno(serialNo);
            cardusedDao.updateByPrimaryKey(cardUsed);
        }
        return prefix+comCode+riskCode+newYear+serialNo;
    }

    private static String noComplete(int ori,int len){
        StringBuffer buf = new StringBuffer();
        len = len - String.valueOf(ori).length();
        for(int i=0;i<len;i++){
            buf.append("0");
        }
        buf.append(ori);
        return buf.toString();
    }

}
